<script lang="ts" setup>
import type { FetchAddressListRes, NewAddressItemReq } from '@/types/api/other'

import { otherApi } from '@/request/api'
import {
  useGetLocation,

  useHideLoading,
  useLoading,
  useRouteGuard,
  useToast,
} from '@/utils'
import pca from '@/utils/pca'
import { onLoad } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty, isNil, pick } from 'lodash-es'
import { computed, reactive, ref } from 'vue'
import { number as znumber, object as zobject, string as zstring } from 'zod'

const id = ref<number>()
const form = reactive<NewAddressItemReq>({
  tit: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  location: '',
  defaultValue: 0,
  locationAddress: '',
})
const pickerData = computed({
  get: () => form.district,
  set: () => {},
})
const list = ref<FetchAddressListRes['data']>([])
const flag = ref<string>('add')
onLoad(async (query) => {
  // const zparse = zobject({
  //   id: zstring().regex(/^\d+$/).transform(Number).optional(),
  // }).safeParse(query)
  // if (!zparse.success) {
  //   return await useRouteGuard()
  // }

  // if ('id' in zparse.data) {
  //   const [err, res] = await to(otherApi.fetchAddress({ id: zparse.data.id! }))
  //   if (!err) {
  //     if (res.data.length) {
  //       id.value = zparse.data.id
  //       Object.assign(form, pick(res.data[0], Object.keys(form)))
  //     }
  //   }
  // }
  await getAddressList()
})
async function getAddressList() {
  useLoading(true)
  const [err, res] = await to(otherApi.fetchAddress({ pageSize: 50 }))
  useHideLoading()
  if (err) {
    return
  }
  list.value = res.data
  if (Array.isArray(res.data) && res.data.length > 0) {
    // list.value 不是空数组时的处理逻辑
    list.value = res.data
    id.value = res.data[0].id
    Object.assign(form, pick(res.data[0], Object.keys(form)))
  }
}
function _handleChangeDefault() {
  form.defaultValue = form.defaultValue === 1 ? 0 : 1
}

function onCityChange(e: Record<string, any>) {
  form.province = e.detail.value[0].text
  form.city = e.detail.value[1].text
  form.district = e.detail.value[2].text
}
async function onGetLocation() {
  const [err, res] = await to(useGetLocation())
  if (err) {
    return
  }
  form.location = res.address
  form.locationAddress = res
}
async function handleSubmit() {
  const zparse = zobject({
    tit: zstring()
      .trim()
      .min(2, { message: '请填写完整姓名' })
      .regex(/^[\u4E00-\u9FA5]{2,20}$/, { message: '请填写2-20位中文姓名' }),
    phone: zstring()
      .trim()
      .min(1, { message: '请填写完整手机号' })
      .regex(/^1[3-9]\d{9}$/, { message: '请填写正确格式手机号' }),
    province: zstring().min(1, { message: '请填写完整收货地区' }),
    city: zstring().min(1, { message: '请填写完整收货地区' }),
    district: zstring().min(1, { message: '请填写完整收货地区' }),
    address: zstring()
      .trim()
      .min(1, { message: '详细地址至少5个字符' })
      .max(100, { message: '详细地址最多100个字符' })
      .regex(/^[a-z0-9\u4E00-\u9FA5\s.,#-]+$/i, {
        message: '详细地址包含非法字符，必须是某楼、单元、门牌号等',
      })
      .regex(/\D/, {
        message: '详细地址不能全是数字,必须是某楼、单元、门牌号等',
      }),
    defaultValue: znumber().default(0),
  }).safeParse(form)
  if (!zparse.success) {
    return useToast(zparse.error.issues[0].message)
  }
  useLoading(true)
  // 更新
  if (!isNil(id.value)) {
    const [err] = await to(
      otherApi.editAddress({
        ...zparse.data,
        id: id.value,
      }),
    )
    if (err) {
      return useHideLoading()
    }
  }
  // 新增
  else {
    const [err] = await to(otherApi.saveAddress(zparse.data))
    if (err) {
      return useHideLoading()
    }
  }
  useHideLoading()
  uni.$emit('refreshAddressList')
  uni.$emit('updateCheckoutAddress', {
    address: form,
    location: form.locationAddress,
  })
  uni.navigateBack()
}
</script>

<template>
  <view class="px-30px py-20px">
    <view class="overflow-hidden rd-16px bg-white pl-20px">
      <uni-forms :model-value="form">
        <uni-forms-item class="" label="收货人" name="tit">
          <input
            v-model="form.tit"
            class="h-100px text-26px"
            type="text"
            placeholder="收货人姓名"
          >
        </uni-forms-item>
        <uni-forms-item class="" label="手机号" name="phone">
          <input
            v-model="form.phone"
            class="h-100px text-26px"
            type="text"
            maxlength="11"
            placeholder="收货人手机号"
          >
        </uni-forms-item>
        <uni-forms-item class="" label="省市区" name="city">
          <uni-data-picker
            v-model="pickerData"
            :localdata="pca"
            :map="{ text: 'name', value: 'name' }"
            popup-title="请选择省市区"
            @change="onCityChange"
          >
            <template #pickslot="{ data }">
              <view class="h-100px flex items-center text-26px">
                <view v-if="isEmpty(data)" class="text-#80">点击选择省市区</view>
                <view
                  v-else
                  class="routine-lh"
                >{{ data.map((x: any) => x.text).join(' ') }}</view>
              </view>
            </template>
          </uni-data-picker>
        </uni-forms-item>
        <uni-forms-item class="!b-none" label="位置信息" name="address">
          <view class="w-hull h-hull" @click="onGetLocation">
            <span v-if="form.location">{{ form.location }}</span>
            <span v-else class="text-gray-400">请授权下单地区</span>

          </view>
        </uni-forms-item>
        <uni-forms-item class="!b-none" label="详细地址" name="address">
          <input
            v-model="form.address"
            class="h-100px text-26px"
            type="text"
            placeholder="收货详细地址"
          >
        </uni-forms-item>
        <!-- <uni-forms-item class="b-none" label="设为默认" name="defaultValue">
            <view class="h-100px flex">
              <view class="ml-a h-100px w-100px flex" @click="handleChangeDefault">
                <radio class="pointer-events-none m-a" :checked="form.defaultValue === 1" color="#f7920d"></radio>
              </view>
            </view>
          </uni-forms-item> -->
      </uni-forms>
    </view>
  </view>

  <!-- <view class="mt-a flex bg-white pt-15px safe-pb-15px">
      <view class="mx-a w-600px btn-primary-black text-36px lh-80px" @click="handleSubmit">保存</view>
    </view> -->

  <view class="fixed bottom-0 w-full flex bg-white pt-15px safe-pb-15px">
    <view
      class="btn-primary-black mx-a w-600px text-36px lh-80px"
      @click="handleSubmit"
    >保存</view>
  </view>
</template>

<style lang="less" scoped>
:deep(.uni-forms) {
  .uni-forms-item {
    --uno: 'items-center b-b-gray-300 b-b-solid !mb-0';
    height: 100rpx;
    border-bottom-width: 1rpx;
  }
}
</style>
